import { Injectable, Injector, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { zip } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { DA_SERVICE_TOKEN, ITokenModel, ITokenService } from '@delon/auth';
import { ALAIN_I18N_TOKEN, MenuService, SettingsService, TitleService } from '@delon/theme';
import { TranslateService } from '@ngx-translate/core';
import { I18NService } from '../i18n/i18n.service';
import { Device } from '@ionic-native/device/ngx';
import { RsocketService } from '@core';
import { environment } from '@env/environment';
import { StorageService } from '@core/storage/storage.sercvice';

/**
 * Used for application startup
 * Generally used to get the basic data of the application, like: Menu Data, User Data, etc.
 */
@Injectable()
export class StartupService {
  constructor(
    private menuService: MenuService,
    private translate: TranslateService,
    @Inject(ALAIN_I18N_TOKEN) private i18n: I18NService,
    private settingService: SettingsService,
    private titleService: TitleService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    private httpClient: HttpClient,
    private injector: Injector,
    private rsocketService: RsocketService,
    private device: Device,
    private storageService: StorageService
  ) {}

  private viaHttp(resolve: any, reject: any): void {
    const tokenData: ITokenModel = this.tokenService.get() as ITokenModel;
    if (!tokenData.token) {
      this.translate.setDefaultLang(this.i18n.defaultLang);
      this.injector.get(Router).navigateByUrl('/passport/login');
      resolve({});
      return;
    }
    zip(
      this.httpClient.get(`assets/tmp/i18n/${this.i18n.defaultLang}.json`),
      this.httpClient.get(`${environment.sys.ctx}/admin/getSysInfo`, { headers: { Authorization: `Bearer ${tokenData.token}` } }),
      this.httpClient.get(`${environment.im.ctx}/imInfo/findByLoginUser`, { headers: { Authorization: `Bearer ${tokenData.token}` } }),
    ).pipe(
      catchError((res) => {
        console.warn(`StartupService.load: Network request failed`, res);
        resolve(null);
        return [];
      })
    ).subscribe(([langData, appData, imInfo]) => {
      this.storageService.set("imInfo", imInfo)
      // Setting language data
      this.translate.setTranslation(this.i18n.defaultLang, langData);
      this.translate.setDefaultLang(this.i18n.defaultLang);

      // Application data
      const res: any = appData;
      // Application information: including site name, description, year
      this.settingService.setApp(res.app);
      // User information: including name, avatar, email address
      this.settingService.setUser(res.user);
      // Menu data, https://ng-alain.com/theme/menu
      //this.menuService.add(res.menus);
      // 设置页面标题的后缀
      this.titleService.default = '';
      this.titleService.suffix = res.app.name;

      this.storageService.set("platform", {
        device: this.device.platform,
        deviceModel: this.device.model,
        clientVersion: environment.version
      })
      this.rsocketService.connect();
    },
    () => { },
    () => {
      resolve(null);
    });
  }
  
  private viaMockI18n(resolve: any, reject: any): void {
    this.httpClient
      .get(`assets/tmp/i18n/${this.i18n.defaultLang}.json`)
      .subscribe(langData => {
        this.translate.setTranslation(this.i18n.defaultLang, langData);
        this.translate.setDefaultLang(this.i18n.defaultLang);

        this.viaMock(resolve, reject);
      });
  }
  
  private viaMock(resolve: any, reject: any): void {
    const tokenData = this.tokenService.get();
    if (!tokenData.token) {
      this.injector.get(Router).navigateByUrl('/passport/login');
      resolve({});
      return;
    }
    // mock
    const app: any = {
      name: `ng-alain`,
      description: `Ng-zorro admin panel front-end framework`
    };
    const user: any = {
      name: 'Admin',
      avatar: './assets/tmp/img/avatar.jpg',
      email: 'cipchk@qq.com',
      token: '123456789'
    };
    // Application information: including site name, description, year
    this.settingService.setApp(app);
    // User information: including name, avatar, email address
    this.settingService.setUser(user);
    // Menu data, https://ng-alain.com/theme/menu
    this.menuService.add([
      {
        text: 'Main',
        group: true,
        children: [
          {
            text: 'Dashboard',
            link: '/dashboard',
            icon: { type: 'icon', value: 'appstore' }
          }
        ]
      }
    ]);
    // Can be set page suffix title, https://ng-alain.com/theme/title
    this.titleService.suffix = app.name;

    this.rsocketService.connect();
    resolve({});
  }

  load(): Promise<any> {
    // only works with promises
    // https://github.com/angular/angular/issues/15088
    return new Promise((resolve, reject) => {
      // http
      this.viaHttp(resolve, reject);
      // mock：请勿在生产环境中这么使用，viaMock 单纯只是为了模拟一些数据使脚手架一开始能正常运行
      //this.viaMockI18n(resolve, reject);

    });
  }
}
